package com.wing.res.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.common.enums.MaintenanceEnum;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.product.model.response.ProductPlanningTreeVo;
import com.wing.product.model.response.ProductVO;
import com.wing.res.model.entity.BenchmarkBook;
import com.wing.res.model.entity.ResBenchmarkBookBom;
import com.wing.res.model.entity.ResBenchmarkBookEchnology;
import com.wing.res.model.entity.ResBenchmarkBookQuality;
import com.wing.res.model.request.ResBenchmarkBookAddForm;
import com.wing.res.model.response.BenchmarkBookProcessEpVO;
import com.wing.res.model.response.ResBenchmarkBookDetailVo;
import com.wing.res.service.BenchmarkBookService;
import com.wing.res.service.ResBenchmarkBookBomService;
import com.wing.res.service.ResBenchmarkBookEchnologyService;
import com.wing.res.service.ResBenchmarkBookQualityService;
import com.wing.storage.model.entity.ProductInventory;
import com.wing.storage.service.ProductInventoryService;
import com.wing.utils.ExcelUtils;
import com.wing.web.annotation.RequestObjectFieldIgnore;
import com.wing.web.db.config.util.DynamicDataSource;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 基准书-controller
 *
 * @author xiayang
 */
@Validated
@Api(value = "基准书管理", tags = "#/res/benchmarkBook/benchmarkBook")
@RestController("benchmarkBookController")
@RequestMapping("benchmarkBook/admin/benchmarkBook")
@RequiredArgsConstructor
public class BenchmarkBookController {

    private final BenchmarkBookService benchmarkBookService;
    private final ResBenchmarkBookEchnologyService resBenchmarkBookEchnologyService;
    private final ResBenchmarkBookQualityService resBenchmarkBookQualityService;
    private final ResBenchmarkBookBomService resBenchmarkBookBomService;
    private final ProductInventoryService productInventoryService;

    @ApiOperation(value = "查询基准书列表", notes = "搜索")
    @GetMapping("/list")
    public PageResult<BenchmarkBook> list(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer limit,
            @RequestParam(name = "skuCode", required = false) String skuCode,
            @RequestParam(name = "code", required = false) String code,
            @RequestParam(name = "bookType", required = false) String bookType,
            @RequestParam(name = "skuName", required = false) String skuName,
            @RequestParam(name = "notStatus", required = false) String notStatus) {
        Page<BenchmarkBook> pg = new Page<>(page, limit);
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("code", code);
        params.put("bookType", bookType);
        params.put("skuCode", skuCode);
        params.put("skuName", skuName);
        params.put("notStatus", notStatus);
        String databaseUser = DynamicDataSource.USER_PREFIX;
        if (StringUtils.isNotBlank(DynamicDataSource.name.get())) {
            databaseUser = databaseUser + "-" + DynamicDataSource.name.get();
        }
        params.put("databaseUser", databaseUser);
        IPage<BenchmarkBook> list = benchmarkBookService.list(pg, params);

        list.getRecords().forEach(info->{
            info.setStatusName(MaintenanceEnum.BenchmarkBookStatus.getNameByCode(info.getStatus()));

            QueryWrapper<ResBenchmarkBookEchnology> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("book_id", info.getId());
            //查询是否工艺规划
            int count = resBenchmarkBookEchnologyService.count(queryWrapper);
            if (count>0){
                info.setIsProcess("是");
            }else{
                info.setIsProcess("否");
            }
            //查询是否质检标准

            QueryWrapper<ResBenchmarkBookQuality> qt = new QueryWrapper<>();
            qt.eq("book_id", info.getId());

            int qtCount = resBenchmarkBookQualityService.count(qt);
            if (qtCount>0){
                info.setIsQuality("是");
            }else{
                info.setIsQuality("否");
            }

            //查询是否bom
            QueryWrapper<ResBenchmarkBookBom> bom = new QueryWrapper<>();
            bom.eq("book_id", info.getId());
            int bomCount = resBenchmarkBookBomService.count(bom);
            if (bomCount>0){
                info.setIsBom("是");
            }else{
                info.setIsBom("否");
            }
        });

        return new PageResult<>(list.getRecords(), list.getTotal());
    }

    @ApiOperation(value = "生成-基准书", notes = "生成-基准书")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/generateBenchmarkBook")
    public JsonResult addBenchmarkBook(@RequestBody ResBenchmarkBookAddForm resBenchmarkBookAddForm) {
        Long l = benchmarkBookService.generateBenchmarkBook(resBenchmarkBookAddForm);
        if (l>0){
            return JsonResult.success(l);
        }else{
            return JsonResult.fail("操作失败！");
        }
    }


    @ApiOperation(value = "基准书-详情", notes = "基准书-详情")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @GetMapping("/detail/{id}")
    public JsonResult benchmarkBookDetail(@PathVariable("id")Long id) {
        Map<String, Object> params = new HashMap<String, Object>();
        String databaseUser = DynamicDataSource.USER_PREFIX;
        if (StringUtils.isNotBlank(DynamicDataSource.name.get())) {
            databaseUser = databaseUser + "-" + DynamicDataSource.name.get();
        }
        params.put("databaseUser", databaseUser);
        ResBenchmarkBookDetailVo benchmarkBookDetailVo = benchmarkBookService.detail(id,params);
        return JsonResult.success(benchmarkBookDetailVo);
    }

    @ApiOperation(value = "修改-基准书", notes = "修改-基准书")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/updateBenchmarkBook")
    public JsonResult updateBenchmarkBook(@RequestBody ResBenchmarkBookAddForm resBenchmarkBookAddForm) {
        if (benchmarkBookService.updateBenchmarkBook(resBenchmarkBookAddForm) > 0) {
            return JsonResult.success("修改成功");
        }
        return JsonResult.fail("修改失败");
    }

    @ApiOperation(value = "修改-状态", notes = "修改-状态")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/benchmarkBookChange/{id}/{status}")
    public JsonResult benchmarkBookChange(@PathVariable("id") Long id, @PathVariable("status") String status) {
        if (benchmarkBookService.benchmarkBookChange(id,status) > 0) {
            return JsonResult.success("修改成功");
        }
        return JsonResult.fail("修改失败");
    }


    @ApiOperation(value = "查询sku-基准书", notes = "sku基准书")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @GetMapping("/getBookInfoBy/{skuId}")
    public JsonResult getBookInfoBy(@PathVariable("skuId") Long skuId) {
        QueryWrapper<BenchmarkBook> benchmarkBookQueryWrapper = new QueryWrapper<>();
        benchmarkBookQueryWrapper.eq("product_detail_id",skuId);
        benchmarkBookQueryWrapper.notIn("status",7);
        return JsonResult.success(benchmarkBookService.list(benchmarkBookQueryWrapper));
    }

    /**
     * 作废基准书
     * @param id
     * @return
     */
    @ApiOperation(value = "作废-基准书", notes = "作废-基准书")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/voidBook/{id}")
    public JsonResult voidBook(@PathVariable("id") Long id) {
        if (benchmarkBookService.voidBook(id) > 0) {
            return JsonResult.success("修改成功");
        }
        return JsonResult.fail("修改失败");
    }


    @ApiOperation(value = "查询-基准书工序", notes = "基准书-工序")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @GetMapping("/getEchnologyBy/{bookId}")
    public JsonResult getEchnologyBy(@PathVariable("bookId") Long bookId) {
        QueryWrapper<ResBenchmarkBookEchnology> echnologyQueryWrapper = new QueryWrapper<>();
        echnologyQueryWrapper.eq("book_id",bookId);
        echnologyQueryWrapper.eq("is_deleted",false);
        return JsonResult.success(resBenchmarkBookEchnologyService.list(echnologyQueryWrapper));
    }



    @ApiOperation(value = "查询-基准书BomList", notes = "基准书-BomList")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @GetMapping("/getBomListBy/{bookId}")
    public JsonResult getBomListBy(@PathVariable("bookId") Long bookId) {
        //1.查询bom信息
        List<ProductPlanningTreeVo> vos = this.resBenchmarkBookBomService.selectBomTreeByBook(bookId);

        //查询库存
        List<ProductInventory> inventoryList = productInventoryService.list();
        if (CollectionUtil.isNotEmpty(vos)) {
            for (ProductPlanningTreeVo vo : vos) {
                //查询出 库存数
                for (ProductInventory productInventory : inventoryList) {
                    if (productInventory.getProductDetailId().equals(vo.getProductDetailId())) {
                        vo.setHaveQuantity(productInventory.getQuantity());
                    }
                }
            }
        }
        return JsonResult.success(vos);
    }


    @ApiOperation(value = "导出基准书工序")
    @GetMapping("/export")
    public void exportBenchmarkBooKProcess(HttpServletResponse response,
                       @RequestParam(name = "bookCode", required = false) String bookCode){
        List<BenchmarkBookProcessEpVO> list = new ArrayList<>();
        Map<String,Object> params = new HashMap<>();
        if(StringUtils.isNotBlank(bookCode)){
            params.put("bookCode", bookCode);
        }

        list = resBenchmarkBookBomService.exportBenchmarkBooKProcess(params);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
        String timestamp = sdf.format(new Date());
        // 生成带时间戳的文件名
        String fileName = "基准书工序_" + timestamp;
        ExcelUtils.export(response,fileName,list, BenchmarkBookProcessEpVO.class);
    }

}
